<template>
  <div>
    <el-dialog v-if="enable" :visible.sync="enable" title="网站编辑">
      <el-form ref="form" label-width="80px">
        <el-form-item label="访问地址">
          <el-input v-model="model.serverName"></el-input>
        </el-form-item>
        <el-form-item label="备注">
            <el-input v-model="model.comment"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="enable = false">取 消</el-button>
        <el-button type="primary" @click="actionGenerate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import yaml from 'js-yaml'
export default {
    data() {
        return {
            enable : false,
            model : { comment:'' },
        };
    },
    methods : {
        /** 打开弹框 */
        open() {
            this.model = { comment:'' };
            this.enable = true;
        },

        /** 创建网站 */
        async actionGenerate() {
            let comDoc = yaml.dump(this.model).trim();
            comDoc = comDoc.split("\n");

            let vhost = [];
            vhost.push('# ADMOOT APACHE VIRTUALHOST CONFIG START');
            for ( let i=0; i<comDoc.length; i++ ) {
                vhost.push(`# ${comDoc[i]}`);
            }
            vhost.push('# ADMOOT APACHE VIRTUALHOST CONFIG END');
            vhost.push('<VirtualHost *:80>');
            vhost.push(`  ServerName ${this.model.serverName}`);
            vhost.push(`</VirtualHost>`);

            let server = this.$store.getters.serverCurrent;
            let client = await server.getSshClient();
            for ( let i=0; i<vhost.length; i++) {
                let cmd = vhost[i].replace(/"/g,'\\"');
                cmd = `echo "${cmd}" >> /etc/apache2/sites-available/${this.model.serverName}.conf`;
                await client.exec(cmd);
            }
            await client.exec('systemctl restart apache2');
            
            this.$emit('update');
            this.enable = false;
        },
    },
}
</script>